import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, AxiosRequestHeaders } from 'axios'
import { showMessage } from './status'
import { ElMessage, ElLoading, LoadingParentElement } from 'element-plus'
import { useRouter } from 'vue-router'
import { useUserStore } from '../store/user'
import { ComponentPublicInstance, ComponentOptionsBase, Ref } from 'vue'

const router = useRouter()
const store = useUserStore()
const baseUrl = '' + import.meta.env.VITE_BASE_API + ''
let loadingInstance: { close: any; setText?: (text: string) => void; removeElLoadingChild?: () => void; handleAfterLeave?: () => void; vm?: ComponentPublicInstance<{}, {}, {}, {}, {}, {}, {}, {}, false, ComponentOptionsBase<any, any, any, any, any, any, any, any, any, {}, {}, string>, {}>; $el?: HTMLElement; originalPosition?: Ref<string>; originalOverflow?: Ref<string>; visible?: Ref<boolean>; parent?: Ref<LoadingParentElement>; background?: Ref<string>; svg?: Ref<string>; svgViewBox?: Ref<string>; spinner?: Ref<string | boolean>; text?: Ref<string>; fullscreen?: Ref<boolean>; lock?: Ref<boolean>; customClass?: Ref<string>; target?: Ref<HTMLElement>; beforeClose?: Ref<(() => boolean) | undefined> | undefined; closed?: Ref<(() => void) | undefined> | undefined }

// 创建一个 axios 实例
const server: AxiosInstance = axios.create({
    // baseURL: '/hp', // API 请求的默认前缀，可根据环境变量自行配置
    baseURL: baseUrl, // 实际请求地址，打包时使用
    headers: {
        Accept: 'application/json'
        // "Content-Type": "application/x-www-form-urlencoded"
    },
    timeout: 10000 // 请求超时时间
})

// axios实例拦截请求
server.interceptors.request.use(
    (config: AxiosRequestConfig) => {
        const token = localStorage.getItem('app_token')
        loadingInstance = ElLoading.service({ fullscreen: true })
        if (token) {
            ;(config.headers as AxiosRequestHeaders).Authorization = token
        }
        return config
    },
    (error: any) => {
        return Promise.reject(error)
    }
)

// axios实例拦截响应
server.interceptors.response.use(
    (response: AxiosResponse) => {
        if (store.load.close) {
            loadingInstance.close()
        } else {
            store.updateState({
                load: { close: true }
            })
        }
        if (response.status == 200) {
            if (response.data.status == 'fail') {
                ElMessage.error(response.data.message)
            }
            if (response.data.code == 1001) {
                localStorage.removeItem('app_token')
                router.push({
                    path: '/login'
                })
            } else {
                return response.data
            }
        }
    },
    // 请求失败
    (error: any) => {
        const { response } = error
        if (response) {
            // 请求已发出，但是不在2xx的范围
            ElMessage.warning(showMessage(response.status))
            return Promise.reject(response.data)
        } else {
            /* console.log(useRouter());
            
            router.push({
                path: '/login'
            }) */
            ElMessage.warning('网络连接异常,请稍后再试!')
        }
    }
)

export default server
